<template>
  <div class="certificate-container">
    <div class="section-title">证书生成</div>
    <el-form :model="certificateForm" :rules="certificateRules" ref="certificateFormRef" label-width="120px" class="certificate-form">
      <el-form-item label="上传文件" prop="file">
        <el-upload
          v-model:file-list="certificateForm.fileList"
          class="certificate-upload"
          :auto-upload="false"
          :limit="1"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              请上传需要处理的文件（支持任意类型）
            </div>
          </template>
        </el-upload>
      </el-form-item>
      
      <el-form-item label="过期时间" prop="expiryTime">
        <el-date-picker
          v-model="certificateForm.expiryTime"
          type="datetime"
          placeholder="选择过期时间"
          style="width: 100%;"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      
      <el-form-item label="组织单位" prop="ou">
        <el-input
          v-model="certificateForm.ou"
          placeholder="请输入组织单位"
        />
      </el-form-item>
      

      
      <el-form-item label="模块选择" prop="modulesId">
        <el-tree
          v-model="certificateForm.modulesId"
          :data="modulesList"
          show-checkbox
          check-strictly
          node-key="id"
          :props="{
            label: 'name',
            children: 'children'
          }"
          :loading="modulesLoading"
          @check="handleModuleCheck"
        />
        <div class="form-tip">请直接选择需要的模块</div>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="generateCertificate" :loading="certificateLoading">生成证书</el-button>
        <el-button @click="resetCertificateForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'CertificateGenerator',
  data() {
    return {
      // 证书生成表单数据
      certificateForm: {
        fileList: [],
        expiryTime: '2025-10-31 00:00:00',
        ou: '飞飞鱼',
        modulesId: [1]
      },
      certificateLoading: false,
      modulesLoading: false,
      modulesList: [],
      certificateRules: {
          file: [
            { required: true, message: '请选择上传文件', trigger: 'change' }
          ],
          expiryTime: [
            { required: true, message: '请选择过期时间', trigger: 'change' }
          ],
          ou: [
            { required: true, message: '请输入组织单位', trigger: 'blur' }
          ],
          modulesId: [
            { 
              validator: (rule, value, callback) => {
                if (!value || value.length === 0) {
                  callback(new Error('请选择模块'))
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ]
        },
      // API基础URL
      baseUrl: 'http://127.0.0.1:9997'
    }
  },
  
  mounted() {
    // 组件挂载时获取模块列表
    this.getModulesList()
  },
  
  methods: {
      // 处理模块选择 - 确保选择时不会产生Promise错误
      handleModuleCheck(data, node) {
        // 使用一个临时变量存储当前选中的ID列表
        let newModulesId = [...this.certificateForm.modulesId]
        this.certificateForm.modulesId = [...node.checkedKeys]
        // 简化处理逻辑，只做基础的ID收集，避免复杂递归导致的Promise错误
        this.$nextTick(() => {
          try {
            // 为了解决表单验证问题，我们添加一个简单的验证逻辑
            if (this.$refs.certificateFormRef) {
              // 直接更新验证状态，避免validateField可能带来的问题
              const field = this.$refs.certificateFormRef.fields.find(f => f.prop === 'modulesId')
              if (field) {
                field.validateState = this.certificateForm.modulesId.length > 0 ? 'success' : ''
                field.validateMessage = ''
              }
            }
          } catch (error) {
            console.error('表单验证更新失败:', error)
          }
        })
      },
      
      // 根据ID查找节点
      findNodeById(nodes, id) {
        for (const node of nodes) {
          if (node.id === id) {
            return node
          }
          if (node.children && node.children.length > 0) {
            const found = this.findNodeById(node.children, id)
            if (found) return found
          }
        }
        return null
      },
      
      // 递归添加所有父节点ID
      addAllParentIds(nodes, parentId, idSet) {
        if (!parentId) return
        
        // 添加当前父节点ID
        idSet.add(parentId)
        
        // 查找当前父节点，获取其上一级父节点
        const parentNode = this.findNodeById(nodes, parentId)
        if (parentNode && parentNode.parentId) {
          // 递归处理上一级父节点
          this.addAllParentIds(nodes, parentNode.parentId, idSet)
        }
      },
    
    // 获取模块列表
    async getModulesList() {
      this.modulesLoading = true
      try {
        const response = await axios.get(`${this.baseUrl}/license/getLicenseModules`)
        this.modulesList = response.data
      } catch (error) {
        console.error('获取模块列表失败:', error)
        this.$message.error('获取模块列表失败，请稍后重试')
      } finally {
        this.modulesLoading = false
      }
    },
    
    // 扁平化模块列表（保留功能但暂时不使用）
      flattenModules(modules) {
        let result = []
        
        function processModule(module) {
          result.push(module)
          if (module.children && module.children.length > 0) {
            module.children.forEach(child => processModule(child))
          }
        }
        
        modules.forEach(module => processModule(module))
        return result
      },
    
    // 生成证书
    async generateCertificate() {
      // 简单验证文件是否上传
      if (!this.certificateForm.fileList || this.certificateForm.fileList.length === 0) {
        this.$message.error('请选择要上传的文件')
        return
      }
      
      this.certificateLoading = true
      try {
        const formData = new FormData()
        
        // 添加文件（必须是Blob类型）
        const file = this.certificateForm.fileList[0].raw
        if (file && file instanceof Blob) {
          formData.append('file', file)
        } else {
          this.$message.error('文件格式错误')
          this.certificateLoading = false
          return
        }
        
        // 按照API要求，构建JSON格式的licenseParams
        const licenseParamsObj = {
          expiryTime: this.certificateForm.expiryTime || '',
          ou: this.certificateForm.ou || '',
          state: '', // 根据API要求添加，暂时为空字符串
          modulesId: Array.isArray(this.certificateForm.modulesId) 
            ? this.certificateForm.modulesId 
            : []
        }
        
        // 将JavaScript对象转换为JSON字符串
        const licenseParamsJson = JSON.stringify(licenseParamsObj)
        // 添加字符串参数，确保是正确的字符串类型
        formData.append('licenseParams', new Blob([licenseParamsJson], { type: 'application/json' }))
        
        // 移除Content-Type，让浏览器自动设置正确的multipart/form-data边界
        const response = await axios.post(
          `${this.baseUrl}/license/generateLicense`,
          formData,
          {
            responseType: 'blob' // 重要：设置响应类型为blob
          }
        )
        
        // 处理下载证书文件
        this.handleCertificateDownload(response)
        this.$message.success('证书生成成功')
      } catch (error) {
        console.error('证书生成失败:', error)
        this.$message.error('证书生成失败：' + (error.response?.data?.message || error.message || '未知错误'))
      } finally {
        this.certificateLoading = false
      }
    },
    
    // 处理证书文件下载
    handleCertificateDownload(response) {
      // 创建Blob对象
      const blob = new Blob([response.data], { type: 'application/x-x509-ca-cert' })
      
      // 创建下载链接并触发下载
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `license_${new Date().getTime()}.lic`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    },
    
    // 重置证书表单
      resetCertificateForm() {
        if (this.$refs.certificateFormRef) {
          this.$refs.certificateFormRef.resetFields()
        }
        this.certificateForm.fileList = []
        this.certificateForm.modulesId = []
      }
    }
}
</script>

<style scoped>
.certificate-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.certificate-form {
  max-width: 800px;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.certificate-upload {
  display: block;
}

.el-form-item {
  margin-bottom: 24px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}
</style>